package org.steve.betterattack;

import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentWrapper;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.steve.betterattack.Abilities.Ability;

import java.util.*;

public class Weapons {
    BetterAttack plugin;
    String displayName;
    List<Ability>abilities;
    int star;
    Material material;
    String id;
    int maxLevel;
    double damage;
    double damageLevelAdd=0;
    double attackSpeed=1.6;
    double attackSpeedLevelAdd=0;
    int durability;
    int durabilityLevelAdd=0;
    double SuccessAttackRateAdd=0;
    double SuccessAttackRateAddLevelAdd=0;
    double CritRate=0.05;
    double CritRateLevelAdd=0;
    double CritDamage=0.5;
    double CritDamageLevelAdd=0;
    double LevelRepression=0;
    double LevelRepressionLevelAdd=0;
    double LevelRepressionLimit=0;
    String description="";
    Map<Enchantment, Integer>enchantments=new HashMap<>();

    public Weapons(BetterAttack plugin, ConfigurationSection config) throws Exception {
        abilities=new ArrayList<>();
        this.plugin=plugin;
        id=config.getName();
        material=Material.getMaterial(config.getString("material").toUpperCase());
        star=config.getInt("star");
        displayName=config.getString("name");
        maxLevel=config.getInt("max_level");

        damage=((ConfigurationSection) config.get("damage")).getDouble("value");
        damageLevelAdd=((ConfigurationSection) config.get("damage")).getDouble("add_per_level");
        if (config.contains("attack_speed")){
            attackSpeed=((ConfigurationSection) config.get("attack_speed")).getDouble("value");
            attackSpeedLevelAdd=((ConfigurationSection) config.get("attack_speed")).getDouble("add_per_level");
        }

        if (config.contains("durability")){
            durability = ((ConfigurationSection) config.get("durability")).getInt("value");
            durabilityLevelAdd = ((ConfigurationSection) config.get("durability")).getInt("add_per_level");
        }
        else{
            durability=material.getMaxDurability();
        }

        if (config.contains("success_attack_rate_add")){
            SuccessAttackRateAdd = ((ConfigurationSection) config.get("success_attack_rate_add")).getDouble("value");
            SuccessAttackRateAddLevelAdd =  ((ConfigurationSection) config.get("success_attack_rate_add")).getDouble("add_per_level");
        }

        if (config.contains("crit_rate")){
            CritRate = ((ConfigurationSection) config.get("crit_rate")).getDouble("value");
            CritRateLevelAdd = ((ConfigurationSection) config.get("crit_rate")).getDouble("add_per_level");
        }

        if (config.contains("crit_damage")){
            CritDamage = ((ConfigurationSection) config.get("crit_damage")).getDouble("value");
            CritDamageLevelAdd = ((ConfigurationSection) config.get("crit_damage")).getDouble("add_per_level");
        }

        if (config.contains("level_repression")){
            LevelRepression = ((ConfigurationSection) config.get("level_repression")).getDouble("value");
            LevelRepressionLevelAdd = ((ConfigurationSection) config.get("level_repression")).getDouble("add_per_level");
        }

        if (config.contains("level_repression_limit")){
            LevelRepressionLimit = config.getDouble("level_repression_limit");
        }

        if (config.contains("description")){
            description = config.getString("description");
        }

        ConfigurationSection section = config.getConfigurationSection("enchant");
        for(String name:section.getKeys(false)){
            Enchantment enchantment=new EnchantmentWrapper(name.toLowerCase());
            if(enchantment==null){
                plugin.getLogger().info("武器的附魔属性无效！enchant: "+name);
                continue;
            }
            enchantments.put(enchantment, section.getInt(name));
        }

        // 强化配方
        {
            boolean auto = false;
            ArrayList<String> autolist = null;

            for (int i = 0; i < maxLevel; i++) {
                if(i < config.getList("smithing").size()) {
                    auto = config.getList("smithing").get(i) instanceof String ;//&& ((String) config.getList("smithing").get(i)).equalsIgnoreCase("auto");
                }
                if(plugin.debug) plugin.getLogger().info("正在生成第"+i+"级强化配方："+"_betterattack_" + id + i+"  auto:"+auto);
                if (auto) {
                    if(autolist==null)plugin.getLogger().info("auto标记无效，因为前一个强化内容不存在");
                    else plugin.RegisteredCraftingRecipe.put("_betterattack_" + id + i, new CraftingRecipe(plugin, id, autolist, i));
                }
                else {
                    ArrayList<String> list = (ArrayList<String>) config.getList("smithing").get(i);
                    for (int i1=list.size();i1<8;i1++){
                        list.add("air");

                    }
                    if (list.size()==8) list.add("");
                    list.set(8,"ba."+id);
                    autolist=list;
                    plugin.RegisteredCraftingRecipe.put("_betterattack_" + id + i, new CraftingRecipe(plugin, id, list, i));
                }
            }
        }
    }
    public ItemStack getItemStack(int level){
        ItemStack itemStack=new ItemStack(material);
        ItemMeta im=itemStack.getItemMeta();
        im.setDisplayName(displayName);
        im.setLore(getLore(level));
        im.getPersistentDataContainer().set(new NamespacedKey(plugin,"id"), PersistentDataType.STRING,id);
        im.getPersistentDataContainer().set(new NamespacedKey(plugin,"abilities_status"), PersistentDataType.STRING,"ready");
        im.getPersistentDataContainer().set(new NamespacedKey(plugin,"type"), PersistentDataType.STRING,"weapon");
        im.getPersistentDataContainer().set(new NamespacedKey(plugin,"level"), PersistentDataType.INTEGER,level);
        im.addAttributeModifier(Attribute.GENERIC_ATTACK_SPEED,new AttributeModifier(UUID.randomUUID(),"BetterAttack",attackSpeed+level*attackSpeedLevelAdd, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND));
        im.addAttributeModifier(Attribute.GENERIC_ATTACK_DAMAGE,new AttributeModifier(UUID.randomUUID(),"BetterAttack",damage+level*damageLevelAdd, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlot.HAND));
        // 附魔
        {
            for(Enchantment enchantment:enchantments.keySet()){
                im.addEnchant(enchantment,enchantments.get(enchantment),true);
            }
        }
        itemStack.setItemMeta(im);
        return itemStack;
    }
    public double getCritTimes(int level){
        double critRate=CritRate+level*CritRateLevelAdd;
        if(plugin.random.nextDouble()<critRate){
            return CritDamage+level*CritDamageLevelAdd;
        }
        else{
            return 0;
        }
    }
    public List<String> getLore(int level){
        String s="§e";
        for(int i=0;i<star;i++)s+='★';
        List<String> lore=new ArrayList<>();
        lore.add(s);
        lore.add("等级："+level);
        if(description!="") lore.add("§3" + description);
        lore.add("§3拿在手上时，输入§6/betterattack iteminfo§3查看详细信息");
        return lore;
    }
}
